from setux.core.package import CommonPackager
from setux.logger import info, error


# pylint: disable=no-member


class Distro(CommonPackager):
    manager = 'flatpak'

    pkgmap = dict(
        kicad    = 'org.kicad_pcb.KiCad',
        freecad  = 'org.freecadweb.FreeCAD',
        openscad = 'org.openscad.OpenSCAD',
    )

    def ls(self):
        ret, out, err = self.run('flatpak list')
        for line in out[1:]:
            try:
                n, a, v, b, i = line.split()
                yield n, v
            except: pass

    def do_init(self):
        ret, out, err = self.run('flatpak --version')
        if ret==0: return
        self.target.Package.install('flatpak')
        self.run('''
            flatpak remote-add --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo
        ''')
        info(' * REBOOT needed *')

    def do_install(self, pkg, ver=None):
        ret, out, err = self.run(f'flatpak install -y flathub {pkg}')

    def do_installed(self):
        for n, v in self.ls():
            yield n , v

    def do_installable(self):
	# flatpak search --columns=description
        ret, out, err = self.run('flatpak remote-ls flathub')
        if ret!=0:
            error('\n'.join(out))
            return

        for line in out:
            try:
                name, app, inst = line.split()
                yield name.strip(), inst.strip()
            except: pass

    def do_remove(self, pkg):
        self.run(f'flatpak uninstall {pkg}')

    def do_cleanup(self):
        pass

    def do_update(self):
        pass

